﻿$(function () {
    RepoShow()
})



var index = 1;
var size = 100;

function RepoShow() {
    layui.use(['form', 'table'], function () {
        var table = layui.table;

        var reportlossesNo = $("#reportlossesNos").val()
        var reportlossesType = $("#reportlossesTypes").val()
        var documentState = $("#documentState").val()

        $.ajax({
            url: '../Reportlosses/GEtReportlossesShow',
            type: 'get',
            data: {
                reportlossesNo: reportlossesNo,
                reportlossesType: reportlossesType,
                documentState: documentState,
                index: index,
                size: size,
            },
            success: function (res) {
                var list = '';
                var parsedData = JSON.parse(res);
                console.log(parsedData)
                if (parsedData.code === 0) {
                    table.render({
                        elem: showReportlosses, // 对应 HTML 中表格的 id
                        data: parsedData.data.list, // 绑定获取到的数据
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                        page: true,
                        limit: 8,
                        limits: [8, 15, 20],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'reportlossesNo', title: '报损单号' },
                            { field: 'productName', title: '产品名称' },
                            { field: 'productNo', title: '产品编号' },
                            { field: 'batch', title: '批次' },
                            { field: 'productSpec', title: '规格' },
                            { field: 'reportNum', title: '数量' },
                            { field: 'warehouseName', title: '仓库' },
                            { field: 'wlocator', title: '原库位' },
                            { field: 'wRepolocator', title: '报损库位' },
                            { field: 'reportlossesType', title: '报损类型' },
                            {
                                field: 'documentState', title: '状态',
                                templet: function (d) {
                                    if (d.documentState === 1) {
                                        return '等待审核';
                                    } else if (d.documentState === 2) {
                                        return '审核成功';
                                    } else if (d.documentState === 3) {
                                        return '审核失败';
                                    }
                                }
                            },
                            { field: 'examinePeople', title: '审核人' },
                            {
                                field: 'examineTime', title: '审核时间', 
                                templet: function (d) {
                                    if (d.examineTime) {
                                        return d.examineTime.split('T')[0];
                                    }
                                    return 
                                }
                            },
                            {
                                field: '', title: '操作', width: 200, templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick=" editDataFind(' + d.reportlossesId + ')"><i class="layui-icon layui-icon-search"></i>查看</a> ' +
                                        '<a class="layui-btn layui-btn-sm layui-btn-primary" lay-on=s"test-page-edit" onclick="updateData(' + d.reportlossesId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +

                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="reportRangeDel(' + d.reportlossesId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="storageaudit(' + d.reportlossesId + ')"><i class="layui-icon layui-icon-share"></i>审核</a>' ;
                                }
                            }
                        ]]
                    })
                }
                
                $("#data").html(list);
                tacount = parsedData.data.tacount;
            }
        })


    })
}


//入库编辑
window.updateData = function (reportlossesId) {
    localStorage['reportlossesId'] = reportlossesId;
    location.href = '/Reportlosses/UpdaetReportlossesView';
}



//逻辑删除
window.reportRangeDel = function (reportlossesId)

{
    var obj = JSON.stringify({
        "reportlossesId": reportlossesId
    })

    layer.confirm('确定要删除该条数据吗？', function (index)

    {

        $.ajax({
            type: 'post',
            url: '../Reportlosses/ReportRangeDel',
            //contentType: 'application/json',//浏览器里报415错
            data: { data:obj, token: localStorage.getItem("token") },
            success: function (res) {
                if (res != "") {
                    layer.msg('删除成功', { icon: 1 });
                    RepoShow()
                    return;
                } else {
                    layer.alert("删除失败!");
                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }

        })
        layer.close(index);
    })

}
var obj = {
    reportlossesId: '',
    reportlossesNo: '',
    reportlossesType: "",
    associateNumber: '',
    singleMaker: '',
    makeTime: '',
    moveRemark: '',
    documentState: '',
    examineReason: '',
    examinePeople: '',
    wRepolocator: "",

}

//报损详情查看
layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;

    //报损详情弹框
    window.editDataFind = function (reportlossesId) {
        // 发送AJAX请求获取数据
        $.ajax({
            type: 'get',
            url: '../Reportlosses/ReportlossesDetails',
            data: {
                reportlossesId: reportlossesId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                console.log(res)
                const { data } = JSON.parse(res);
                if (data) {
                    const { reportLists } = data;
                    var storage = data;
                    console.log(storage);
                    console.log(reportLists);
                    // 反填表单的函数
                    fillForm(storage)
                    // 渲染表格的函数
                    renderTable(reportLists)
                    //resolve(storage, reportLists)
                }
                else {
                    layui.layer.msg(res.message, { icon: 2 });
                    reject(res.message);
                }

            },
            error: () => {
                layui.layer.msg('获取用户信息失败，请稍后重试', { icon: 2 });
                reject('获取用户信息失败');
            }
        })
        layer.open({
            type: 1,
            title: '报损详情',
            content: `
                      <form class="layui-form" action="">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">入库单号</label>
            <div class="layui-input-inline">
                <input type="text" name="reportlossesNo" id="reportlossesNo" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库单类型</label>
            <div class="layui-input-inline">
                <input type="text" id="reportlossesType" name="reportlossesType" autocomplete="off" class="layui-input">
            </div>
        </div>
       
    </div>

    
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">关联单号：</label>
            <div class="layui-input-inline">
                <input type="text" name="associateNumber" id="associateNumber" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="examinePeople" id="examinePeople" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
                <input type="text" name="makeTime" id="makeTime" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="moveRemark" id="moveRemark" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">审核原因</label>
        <div class="layui-input-block">
            <textarea name="examineReason" id="examineReason" placeholder="请输入审核原因" class="layui-textarea"></textarea>
        </div>
    </div>
    <table class="layui-hide" id="repositProduct" lay-filter="test"></table>
</form>`,
            area: ['1500px', '900px'],
            success: function () {
               
            }
        });
    };


    var obj = {
        reportlossesId: 0,
        storageStatus: '',
        examineReason: '',
        examinePeople: '',
        examineTime: '',
        createName: '',
        createTime: '',
        updateName: '',
        deleteName: '',
        deleteTime: '',
        moveRemark: '',
        singleMaker:"",
    }

    function fillForm(storage) {
        $("#reportlossesNo").val(storage.reportlossesNo);
        $("#reportlossesType").val(storage.reportlossesType);
        $("#associateNumber").val(storage.associateNumber);
        $("#singleMakers").val(storage.singleMaker);
        const date = new Date(storage.makeTime);
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        $('#makeTime').val(year + "-" + month + "-" + day);
        $("#moveRemark").val(storage.moveRemark);
        $("#wRepolocator").val(storage.wRepolocator);
        $("#examinePeople").val(storage.examinePeople)
        $("#storageStatus").val(storage.storageStatus)
        $("#examineReason").val(storage.examineReason)
        console.log(storage)

        obj.singleMaker = storage.singleMaker
        obj.reportlossesId = storage.reportlossesId
        obj.storageStatus = storage.storageStatus
        obj.examineReason = storage.examineReason
        obj.examinePeople = storage.examinePeople
        obj.examineTime = storage.examineTime
        obj.createName = storage.createName
        obj.createTime = storage.createTime
        obj.updateName = storage.updateName
        obj.deleteName = storage.deleteName
        obj.deleteTime = storage.deleteTime
        console.log(obj)

    }



    function renderTable(reportLists) {
        console.log(reportLists)
        var reportlossesId = reportLists[0].reportlossesId
        console.log(reportlossesId)
        layui.use('table', function () {
            var table = layui.table;
            //查询
            $.ajax({
                url: '/Reportlosses/ReportlossesDetails',
                type: 'get',
                data: {
                    reportlossesId: reportlossesId,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    var obj = JSON.parse(res);
                    if (obj.code === 0) {
                        var inst = table.render({
                            elem: "#repositProduct",
                            data: reportLists,
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'productNo', title: '产品编号' },
                                { field: 'productName', title: '产品名称' },
                                { field: 'productSpec', title: '规格' },
                                { field: 'batch', title: '批次' },
                                { field: 'price', title: '单价' },
                                { field: 'reportNum', title: '数量', edit: 'text' },
                                { field: 'binLocationName', title: '当前库位' }
                            ]]
                        })
                    } else {
                        console.log(res.msg);
                    }
                }, error: function () {
                    console.log("获取数据失败");
                    // 可以考虑显示一个错误消息给用户
                }
            })
        })
    }

    // 审批
    window.storageaudit= function (reportlossesId) {
            // 发送AJAX请求获取数据
            $.ajax({
                type: 'get',
                url: '../Reportlosses/ReportlossesDetails',
                data: {
                    reportlossesId: reportlossesId,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    console.log(res)
                    const { data } = JSON.parse(res);
                    if (data) {
                        const { reportLists } = data;
                        var storage = data;
                        console.log(storage);
                        console.log(reportLists);
                        // 反填表单的函数
                        fillForm(storage)
                        // 渲染表格的函数
                        renderTable(reportLists)
                        resolve(storage, reportLists)
                    }
                    else {
                        layui.layer.msg(res.message, { icon: 2 });
                        reject(res.message);
                    }

                },
                error: () => {
                    layui.layer.msg('获取用户信息失败，请稍后重试', { icon: 2 });
                    reject('获取用户信息失败');
                }
            })
        layer.open({
            type: 1,
            title: '报损单审核',
            content: `
                      <form class="layui-form" action="">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">入库单号</label>
            <div class="layui-input-inline">
                <input type="text" name="reportlossesNo" id="reportlossesNo" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库单类型</label>
            <div class="layui-input-inline">
                <input type="text" id="reportlossesType" name="reportlossesType" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库状态</label>
            <div class="layui-input-inline">
                <input type="text" id="documentState" name="documentState" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">关联单号：</label>
            <div class="layui-input-inline">
                <input type="text" name="associateNumber" id="associateNumber" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="examinePeople" id="examinePeople" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
                <input type="text" name="makeTime" id="makeTime" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="moveRemark" id="moveRemark" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">审核原因</label>
        <div class="layui-input-block">
            <textarea name="examineReason" id="examineReason" placeholder="请输入审核原因" class="layui-textarea"></textarea>
        </div>
    </div>
    <table class="layui-hide" id="repositProduct" lay-filter="test"></table>
    <div class="layui-form-item" style="text-align:center;margin-top:50px">
        <button class="layui-btn" lay-submit lay-filter="demo-login">审核通过</button>
        <button class="layui-btn" lay-submit lay-filter="demo-false">审核不通过</button>
        <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Warehouse/StorageShow'">取消</button>
    </div>
</form>`,
            area: ['1500px', '900px'],
            success: function () {
                var obj1 = {
                    reportlossesId: 0,
                    documentState: '',
                    examineReason: '',
                    examinePeople: '',
                };
                // 对弹层中的表单进行初始化渲染
                //form.render();
                // 审核通过
                form.on('submit(demo-login)', function (data) {
                    var field = data.field;
                    console.log(obj)
                    obj1.reportlossesId = reportlossesId
                    console.log(obj1.reportlossesId)
                    obj1.examineReason = field.examineReason
                    console.log(obj1.examineReason)
                    obj1.documentState = 2
                    obj1.examinePeople = "yu"
                    $.ajax({
                        url: '/Reportlosses/ReportlossesAuid',
                        type: 'post',
                        data: { obj1, token: localStorage.getItem("token") },
                        success: function (res) {
                            var res = JSON.parse(res)
                            console.log(field)
                            console.log(res)
                            if (res.code == 1) {
                                layer.alert("审批成功");
                                location.reload();
                                return;
                            }
                            else {
                                layer.alert("操作失败");
                            }
                        }
                    })
                    return false; // 阻止默认 form 跳转
                });
                // 审核不通过
                form.on('submit(demo-false)', function (data) {
                    var field = data.field;
                    obj1.reportlossesId = obj.reportlossesId
                    obj1.examineReason = field.examineReason
                    obj1.documentState = 3
                    $.ajax({
                        url: '/Reportlosses/ReportlossesAuid',
                        type: 'post',
                        data: { obj1, token: localStorage.getItem("token") },
                        success: function (res) {
                            var res = JSON.parse(res)
                            console.log(field)
                            console.log(res)
                            if (res.code == 1) {
                                layer.alert("审批不通过");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                                return;
                            }
                            else {
                                layer.alert("操作失败");
                            }
                        }
                    })
                    return false; // 阻止默认 form 跳转
                });
            }
        });
    };

})



// 点击批量删除按钮的事件处理
$('#batchDeleteBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('showReportlosses');
    var selectedIds = checkStatus.data.map(function (item) {
        return item.reportlossesId;
    });
    console.log(selectedIds)
    if (selectedIds.length === 0) {
        layer.msg('请至少选择一条要删除的数据', { icon: 2 });
        return;
    }
    layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
        // 发送Ajax请求到后端，传递选中的id数组进行删除操作
        //var reportlossesId = {
        //    reportlossesId: selectedIds
        //}
        console.log(selectedIds)
        $.ajax({
            url: '/Reportlosses/ReportProductRangeDel', // 后端批量删除接口地址，根据实际调整
            type: 'post',
            data: {
                reportlossesId: selectedIds,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                if (res.code > 0) {
                    layer.msg('批量删除成功', { icon: 1 });
                    RepoShow()
                } else {
                    layer.msg('批量删除失败：' + res.message, { icon: 2 });
                }
                layer.close(index);
            },
            error: function () {
                layer.msg('请求出错，请稍后再试', { icon: 2 });
                layer.close(index);
            }
        });
    });
});